package com.app.login.controller;

import com.app.login.service.LoginService;
import com.app.store.service.StoreService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by song on 2018/1/9.
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    private static Logger log = Logger.getLogger(LoginController.class);
    @Autowired
    private LoginService loginService;
    @Autowired
    private StoreService storeService;
    /**
     * 用户登录
     */
    @ResponseBody
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public ModelAndView login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletRequest request, HttpServletResponse response){
        ModelAndView errorVeiw = new ModelAndView("redirect:/login/login.jsp");
        try {
            log.info("--------------------------username:"+username+"------password:"+password);
            if(StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)){
                boolean result = loginService.verification(username,password);
                if(result){
                    ModelAndView successView = new ModelAndView("/uploading/uploadFile");
                    HttpSession session = request.getSession();
                    String sessionId = session.getId();
                    String source = "scm";
                    List<String> list = storeService.getServerVersionList(source);
                    log.info("--------------------------sessionId:"+sessionId);
                    session.setAttribute("username",username);
                    successView.addObject("list",list);
                    return successView;
                }
            }
        }catch (Exception e){
            e.getMessage();
            log.error(e.getMessage());
            errorVeiw.addObject("errorMsg","登录失败，请联系管理员");
            return errorVeiw;
        }
        errorVeiw.addObject("errorMsg","请输入用户名、密码");
        return errorVeiw;
    }
}
